<template>
  <div class="my-cloud-store">
    <!-- <div class="tabbar">
      <tabs v-model="active" color="#283C79">
        <tab title="进货"></tab>
        <tab title="提货"></tab>
      </tabs>
    </div>-->

    <div class="text">
      <p>云仓库存</p>
      <p class="detail-list" @click="goTo('/store_records')">
        <span>出入明细</span>
        <icon name="arrow" size="14" />
      </p>
    </div>
    <div class="store-list">
      <list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div class="product-item item" v-for="(item,index) in productsList" :key="index">
          <product-item :cover="item.goodsImg ? staticHost + item.goodsImg : ''">
            <div class="product-info" slot="product-item">
              <p>{{item.goodsName}}</p>
              <p class="size">{{item.size}}</p>
              <p class="price">
                <span>￥{{item.presentPrice}}</span>
              </p>
              <div class="detail">
                <p>
                  可提货数量：
                  <span>{{item.num}}</span>
                </p>
                <p>缺货：{{item.stockOutNum}}</p>
                <!-- <p>有下级代理</p> -->
              </div>
            </div>
          </product-item>
          <div class="operation">
            <p @click="goToAddGoods(item)">进货</p>
            <p @click="popupType = 'carryGoods', showPopup = true, selectedAddCart = item">加入到提货</p>
          </div>
        </div>
      </list>
    </div>
    <!-- <div class="tip">进出明细移至右上角</div> -->

    <div class="goto-list">
      <div class="goto-item" @click="goToShoppingMall">
        <p>
          <img src="../img/我要进货@2x.png" alt />
        </p>
        <div>去商城进货</div>
      </div>
      <i></i>
      <div class="goto-item" @click="popupType = 'carryCart', showPopup = true">
        <p>
          <img src="../img/提货订单@2x.png" alt />
        </p>
        <div>提货购物车</div>
        <p class="dot">{{cartList.length}}</p>
      </div>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'carryGoods'">
        <div class="carry-goods">
          <div class="header">加入提货</div>
          <div class="content">
            <product-item
              :cover="selectedAddCart.goodsImg ? staticHost + selectedAddCart.goodsImg : ''"
            >
              <div class="product-info" slot="product-item">
                <p>{{selectedAddCart.goodsName}}</p>
                <p class="size">{{selectedAddCart.size}}</p>
                <p class="price">
                  <span>￥{{selectedAddCart.presentPrice}}</span>
                </p>
                <div class="detail">
                  <p>
                    可提货数量：
                    <span>{{selectedAddCart.num}}</span>
                  </p>
                  <p>缺货：{{selectedAddCart.stockOutNum}}</p>
                </div>
              </div>
            </product-item>
            <div class="carry-number">
              <p>提货数量</p>
              <p>
                <stepper :max="selectedAddCart.num" v-model="selectedGoodsNumber" />
              </p>
            </div>
          </div>
          <div class="carry-goods-operation">
            <p @click="onCancel">取消</p>
            <p @click="onCarryConfirm">确定</p>
          </div>
        </div>
      </div>
      <div v-if="popupType == 'carryCart'">
        <div class="carry-cart">
          <div class="header">提货购物车</div>
          <div class="content">
            <div class="cart-nothing" v-if="cartList.length == 0">暂无商品</div>
            <div class="cart-list" v-if="cartList.length != 0">
              <swipe-cell v-for="(item,index) in cartList" :key="index">
                <div class="product-item">
                  <product-item :cover="item.goodsImg ? staticHost + item.goodsImg : ''">
                    <div class="product-info" slot="product-item">
                      <p>{{item.goodsName}}</p>
                      <p class="size">{{item.size}}</p>
                      <p class="price">
                        <span>￥{{item.presentPrice}}</span>
                      </p>
                      <div class="cart-detail">
                        <p>
                          可提货数量：
                          <span>{{item.num}}</span>
                        </p>
                        <p>
                          <stepper v-model="item.number" :max="item.num" @change="onStepperChange" />
                        </p>
                      </div>
                    </div>
                  </product-item>
                </div>

                <template slot="right">
                  <van-button type="danger" text="删除" @click="deleteFromCart(item.goodsId)" />
                </template>
              </swipe-cell>
            </div>
          </div>
          <div class="carry-cart-operation">
            <p @click="onCancel">取消</p>
            <p @click="onCartConfirm">提货结算</p>
          </div>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
import productItem from "../components/product_item.vue";
import { mapState } from "vuex";
import {
  Tab,
  Tabs,
  Icon,
  Stepper,
  SwipeCell,
  Cell,
  Button,
  Toast,
  List
} from "vant";
import popup from "../components/popup.vue";
import { staticHost } from "../service/HOST.js";

export default {
  components: {
    productItem,
    Tab,
    Tabs,
    Icon,
    popup,
    Stepper,
    SwipeCell,
    Cell,
    vanButton: Button,
    List
  },
  data() {
    return {
      staticHost,
      active: 0,
      showPopup: false,
      popupType: "",
      selectedGoodsNumber: 1,
      agentInfo: {},
      productsList: [],
      cartList: [
        // {
        //   name: "TIMELESS时光番茄口服美白丸",
        //   cate: "一箱 30包",
        //   num: 1
        // }
      ],
      selectedAddCart: {},
      loading: false,
      finished: false,
      pageNumber: 1,
      pageSize: 10
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    })
  },
  watch: {
    // 监听this.showPopup，如果为false时（关闭popup），把popup stepper this.selectedGoodsNumber 清零
    showPopup(newVal) {
      if (!newVal) {
        this.selectedGoodsNumber = 1;
      }
    }
  },
  mounted() {
    // 初始化 购物车 localstorage
    this.cartList = localStorage.getItem("addCarry")
      ? JSON.parse(localStorage.getItem("addCarry"))
      : [];
  },
  methods: {
    // 跳转到商城
    goToShoppingMall() {
      this.$router.push({
        path: "/product_browse",
        query: {
          isDirect: "N"
        }
      });
    },
    // 获取商品列表
    onLoad() {
      this.$http
        .post(this.$urls.JHSPLB, {
          levelId: this.userInfo.agentLevel,
          pageNumber: this.pageNumber,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res.data.code == 200) {
            this.productsList = this.productsList.concat(res.data.data);

            this.pageNumber++;
            this.loading = false;
          } else if (res.data.code == 300) {
            this.loading = false;
            this.finished = true;
          }
        });
    },
    // 购物车商品数量发生变化时
    onStepperChange() {
      // 更新localStorage里的值
      this.saveCartToStorage();
    },
    // 购物车商品列表 保存到 this.cartList
    saveCartToCartList() {
      if (this.selectedAddCart.num == 0) {
        Toast("可提货数量不足，无法提货");
        return false;
      }
      let number = this.selectedGoodsNumber;
      let index = _.findIndex(this.cartList, o => {
        return o.goodsId == this.selectedAddCart.goodsId;
      });



      // 购物车中是否已存在该种商品
      if (index != -1) {
        // 是否超出了可提取数量
        if (number + this.cartList[index].number > this.selectedAddCart.num) {
          Toast("超出了可提货数量");
          return false;
        }
        this.cartList[index].number += number;
      } else {
        this.selectedAddCart.number = number;
        let cartItem = _.cloneDeep(this.selectedAddCart);
        this.cartList.push(cartItem);
      }
      Toast.success("加入成功");
    },
    // 持久化储存 购物车
    saveCartToStorage() {
      localStorage.setItem("addCarry", JSON.stringify(this.cartList));
    },
    // 购物车删除商品
    deleteFromCart(id) {
      let index = _.findIndex(this.cartList, o => {
        return o.goodsId == id;
      });
      this.cartList.splice(index, 1);

      // 更新localStorage里的值
      this.saveCartToStorage();

      Toast.success("删除成功");
    },
    // 购物车跳转到结算（提货结算）
    onCartConfirm() {
      if (this.cartList.length) {
        this.$router.push({
          path: "/settlement",
          query: {
            shopType: "carryAdd"
          }
        });
      } else {
        Toast("提货购物车不能为空");
      }
    },
    // 加入到提货购物车
    onCarryConfirm() {
      this.saveCartToCartList();

      // 更新localStorage里的值
      this.saveCartToStorage();
      this.showPopup = false;
    },

    // // （弃用）
    // onConfirm(value) {
    //   if (this.popupType == "payType") {
    //     this.selectedPayType = value;
    //     // this.payType = this.selectedPayType
    //   } else if (this.popupType == "grade") {
    //     this.selectedAgencyLevel = value;
    //   }
    //   this.showPopup = false;
    //   // this.pageNumber = 1
    //   // this.allList = []

    //   // this.loading = false
    //   // this.finished = false
    // },
    onCancel() {
      this.showPopup = false;
    },
    goToAddGoods(item) {
      this.$router.push({
        path: "/my_store_add_goods",
        query: item
      });
    },
    // 跳转
    goTo(path) {
      this.$router.push({
        path: path
      });
    }
  }
};
</script>

<style scoped>
.text {
  margin-bottom: 5px;
  position: sticky;
  top: 0;
}

.text,
.tip {
  padding: 10px 15px;
  background-color: #fff;
}

.text {
  display: flex;
  justify-content: space-between;
}

.detail-list {
  display: flex;
  align-items: center;
}

.product-info {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 100%;
  padding: 10px 0 10px 10px;
}

.product-info > p:first-child {
  color: #5a5d6c;
}

.store-list {
  border-top: 1px solid var(--line-between-color);
  /* background-color: #fff; */
  padding-bottom: 64px;
}

.store-list .item {
  margin-bottom: 5px;
}

.cart-detail,
.detail {
  flex: 1;
  width: 100%;
  /* position: absolute;
  bottom: 10px; */
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
}

.detail > p:last-child {
  border: 1px solid #283c79;
  border-radius: 3px;
  color: #283c79;
  padding: 0px 5px;
  font-size: 0.8rem;
}

.operation {
  display: flex;
  justify-content: flex-end;
  font-size: 0.8rem;
}

.operation p {
  margin: 10px;
  margin-left: 10px;
  padding: 4px 15px;
  background-color: #283c79;
  border-radius: 120px;
  color: #fff;
}

.operation p:active {
  background-color: rgb(28, 42, 83);
}

.goto-list {
  display: flex;
  position: fixed;
  bottom: 0;
  width: 100%;
}

.goto-list i {
  display: block;
  width: 2px;
  height: 60px;
  background-color: #F7F8FF;
}

.goto-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px 20px;
  background-color: #fff;
}

.goto-item p {
  width: 28px;
  height: 30px;
}

.goto-item img {
  width: 100%;
  height: 100%;
}

.goto-item div {
  margin-left: 4px;
}

.goto-item:active {
  background-color: rgb(238, 238, 238, 0.4);
}

.carry-cart {
  position: relative;
}

.carry-cart .content,
.carry-goods .content {
  /* padding-top: 5px; */
}
.carry-cart .header,
.carry-goods .header {
  padding: 12px;
  /* margin-bottom: 5px; */
  text-align: center;
  color: var(--Emphasize-font);
  font-size: 1.05rem;
  border-bottom: 1px solid var(--line-between-color);
}

.carry-cart .header {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 100;
}

.carry-cart .content {
  /* padding-bottom: 10px; */
  max-height: 435px;
  overflow: scroll;
}

.carry-cart .product-item {
  margin-bottom: 10px;
}

.carry-number {
  padding: 10px 13px;
}

.carry-number p {
  margin-bottom: 10px;
}

.carry-cart-operation,
.carry-goods-operation {
  display: flex;
}
.carry-cart-operation p,
.carry-goods-operation p {
  flex: 1;
  text-align: center;
  padding: 12px;
  position: relative;
}
.carry-cart-operation p:first-child,
.carry-goods-operation p:first-child {
  background-color: #f7f8fa;
}
.carry-cart-operation p:first-child:active,
.carry-goods-operation p:first-child:active {
  background-color: rgb(218, 218, 218);
}
.carry-cart-operation p:last-child,
.carry-goods-operation p:last-child {
  background-color: #283c79;
  color: #fff;
}
.carry-cart-operation p:last-child:active,
.carry-goods-operation p:last-child:active {
  background-color: rgb(29, 43, 85);
}

.carry-cart-operation {
  width: 100%;
  /* position: fixed; */
  bottom: 0;
}

.cart-nothing {
  padding: 20px 0 30px 0;
  text-align: center;
}

.size {
  font-size: 0.9rem;
}

.price {
  margin-top: 5px;
  color: var(--money-up);
}
</style>

<style>
.my-cloud-store .product-item {
  border-bottom: 0;
  background-color: #fff;
}

.my-cloud-store .van-button {
  height: 100%;
}
</style>